/*
 * @Author: wjc
 * @Date: 2025-07-28 09:16:19
 * @LastEditors: wjc
 * @LastEditTime: 2025-10-28 14:38:59
 * @Description:
 */
import { fileURLToPath, URL } from 'node:url'

import { defineViteConfig } from '@nice/vite-config'
import UnoCSS from 'unocss/vite'
import AutoImport from 'unplugin-auto-import/vite'
import ElementPlus from 'unplugin-element-plus/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
import Components from 'unplugin-vue-components/vite'
import { loadEnv } from 'vite'
import { createHtmlPlugin } from 'vite-plugin-html'

export default defineViteConfig(async (config) => {
  const env = loadEnv(config.mode, process.cwd(), '')
  return {
    define: {
      'process.env': env,
    },
    isBuild: config.command === 'build',
    mode: config.mode,
    command: config.command,
    vueTools: false,
    resolve: {
      alias: {
        '@': fileURLToPath(new URL('src', import.meta.url)), // 与package.json保持一致
      },
    },
    pwa: false,
    server: {
      open: true,
      hmr: {
        overlay: true,
      },
      proxy: {
        '/api': {
          target: env.VITE_APP_BASE_API, // 对应自己的接口
          changeOrigin: true,
          ws: true,
          rewrite: (path: string) => path.replace(/^\/api/, ''), // .replace(/^\/api/, '')
        },
      },
    },
    plugins: [
      UnoCSS(),
      AutoImport({
        include: [
          /\.[tj]sx?$/, // .ts, .tsx, .js, .jsx
          /\.vue$/,
          /\.vue\?vue/, // .vue
        ],
        dirs: ['./src'],
        imports: ['vue', 'vue-router'], // 限定范围为 vue
        dts: 'types/auto-import.d.ts', // 自动生成 'auto-import.d.ts'全局声明
      }),
      Components({
        // 按需导入组件，相关组件声明放置于 components.d.ts
        dts: './types/components.d.ts',
        resolvers: [ElementPlusResolver()],
      }),
      // 按需引入样式
      ElementPlus({
        format: 'esm',
      }),
      createHtmlPlugin({
        minify: true,
      }),
    ],
  }
})
